var pcassCode = require('./data.json');

var addressList = pcassCode;
addressList.forEach(item => {
  formatAddresList(item, 1, '');
});

function formatAddresList(addressList, index, province) {
    if (index === 1) {
      //省
      addressList.province = addressList.name;
      addressList.type ='province';
    }
    if (index === 2) {
      //市
      if (addressList.name == '市辖区') {
        addressList.name = province.name;
      }
      addressList.city = addressList.name;
      addressList.type ='city';
    }
    if (index === 3) {
      //区或者县
      addressList.county = addressList.name;
      addressList.type ='county';
    }
    if (index === 4) {
      //街道
      addressList.street = addressList.name;
      addressList.type ='street';
    }
    if (addressList.children) {
      index++;
      addressList.children.forEach(res => {
        formatAddresList(res, index, addressList);
      });
    }
  }

function resolveDistrictPart(districtName, addressData) {
    if(!districtName) {
        return null
    }
    var foundParts = []
    for (let endIndex = districtName.length; endIndex > 1; endIndex--) {
        let distSignature = districtName.slice(0, endIndex);
        let foundDistrict = addressData.find(p => p.name.indexOf(distSignature) >= 0)
        if(foundDistrict) { 
            foundParts.push({
                district: foundDistrict,
                delta: Math.abs(foundDistrict.name.length - distSignature.length)
            })
        }
    }
    foundParts = foundParts.sort((v1, v2) => v1.delta - v2.delta)
    return foundParts[0] || null
}

export function adjustDistrict(provinceName, cityName, countyName) {
    let province = resolveDistrictPart(provinceName, addressList);
    let city = null;
    let county = null;
    if(province) {
        city = resolveDistrictPart(cityName, province.district.children)
    }
    if(city) {
        county = resolveDistrictPart(countyName, city.district.children)
    }
    
    return {
        province: province.district.name || provinceName,
        city: (city ? city.district.name : null) || cityName,
        county: (county ? county.district.name : null) || countyName
    }
}

// console.log(adjustDistrict("福建", "福州市", "台江区"))
// console.log(adjustDistrict("新疆", "乌鲁木齐", "天山区"))
// console.log(adjustDistrict("宁夏", "固原市", null))